package com.baidu.health.filter;

import com.baidu.health.mapper.TbArticleMapper;
import com.baidu.health.mapper.TbLikeMapper;
import com.baidu.health.pojo.TbArticle;
import com.baidu.health.pojo.TbLike;
import com.baidu.health.pojo.resultVo.resultVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.Date;

@Component
public class likeFilter {

    @Autowired
    TbLikeMapper likeMapper;

    @Autowired
    TbArticleMapper articleMapper;

    @RabbitListener(queues = "like",concurrency = "1")
    public void like(@RequestBody TbLike like, Message message, Channel channel)throws Exception{


        TbArticle tbArticle = articleMapper.selectOne(new QueryWrapper<TbArticle>().lambda().eq(TbArticle::getArticleId, like.getArticleId()));

        QueryWrapper<TbLike> wrapper = new QueryWrapper<>();

        wrapper.lambda().eq(TbLike::getUserId,like.getUserId());
        wrapper.lambda().eq(TbLike::getArticleId,like.getArticleId());

        TbLike tbLike = likeMapper.selectOne(wrapper);

        if ( tbLike == null ){
            likeMapper.insert(like);
            tbArticle.setArticleLikeNums(tbArticle.getArticleLikeNums() + 1);
            articleMapper.updateById(tbArticle);
            long deliveryTag = message.getMessageProperties().getDeliveryTag();
            channel.basicAck(deliveryTag,false);
            channel.basicNack(deliveryTag,false,false);
        }else {
            if ( tbLike.getLikeStatus() == 0 ){
                tbLike.setLikeStatus(1);
                tbLike.setUpdateTime(new Date());
                likeMapper.updateById(tbLike);
                tbArticle.setArticleLikeNums(tbArticle.getArticleLikeNums() - 1);
                articleMapper.updateById(tbArticle);
                long deliveryTag = message.getMessageProperties().getDeliveryTag();
                channel.basicAck(deliveryTag,false);
                channel.basicNack(deliveryTag,false,false);
            }else {
                tbLike.setLikeStatus(0);
                tbLike.setUpdateTime(new Date());
                likeMapper.updateById(tbLike);
                tbArticle.setArticleLikeNums(tbArticle.getArticleLikeNums() + 1);
                articleMapper.updateById(tbArticle);
                long deliveryTag = message.getMessageProperties().getDeliveryTag();
                channel.basicAck(deliveryTag,false);
                channel.basicNack(deliveryTag,false,false);
            }
        }


    }

}
